package com.hjy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Preconditions;
import com.hjy.beans.PageQuery;
import com.hjy.beans.PageResult;
import com.hjy.exception.ParamException;
import com.hjy.mapper.SysUserMapper;
import com.hjy.param.UserParam;
import com.hjy.pojo.SysUser;
import com.hjy.util.BeanValidator;
import com.hjy.util.IpUtil;
import com.hjy.util.MD5Util;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysLogService sysLogService;


    public SysUser findSysUser(String name) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",name);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        return sysUser;
    }

    public void save(UserParam param,HttpServletRequest request){
        BeanValidator.check(param);
        if (checkTelephoneExist(param.getTelephone(),param.getId())){
            throw new ParamException("该电话已被占用");
        }
        if (checkEmailExist(param.getMail(),param.getId())){
            throw new ParamException("该邮箱已被占用");
        }

        String password = MD5Util.md5Hash("123456",param.getUsername()) ;

        SysUser user = SysUser.builder().username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
                .password(password).deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();
        SysUser u = (SysUser)request.getSession().getAttribute("user");
        user.setOperator(u.getUsername());
        user.setOperateIp(IpUtil.getRemoteIp(request));
        user.setOperateTime(new Date());

        sysUserMapper.insert(user);
        sysLogService.saveUserLog(null, user);
    }

    public void update(UserParam param,HttpServletRequest request){
        BeanValidator.check(param);
        if (checkTelephoneExist(param.getTelephone(),param.getId())){
            throw new ParamException("该电话已被占用");
        }
        if (checkEmailExist(param.getMail(),param.getId())){
            throw new ParamException("该邮箱已被占用");
        }

        SysUser before = sysUserMapper.selectById(param.getId());
        Preconditions.checkNotNull(before,"待更新的用户不存在");
        SysUser after = SysUser.builder().username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
                .deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).id(param.getId()).build();
        SysUser user = (SysUser)request.getSession().getAttribute("user");
        after.setOperator(user.getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(request));
        after.setOperateTime(new Date());
        sysUserMapper.updateById(after);
        sysLogService.saveUserLog(before, after);

    }

    public boolean checkEmailExist(String mail,Integer userId){
        QueryWrapper<SysUser> wrapper = new QueryWrapper();
        wrapper.eq("mail",mail);
        if (userId>0){
            wrapper.ne("id",userId);
        }
        return sysUserMapper.selectOne(wrapper)!=null;
    }

    public boolean checkTelephoneExist(String telephone,Integer userId){
        QueryWrapper<SysUser> wrapper = new QueryWrapper();
        wrapper.eq("telephone",telephone);
        if (userId>0&&userId!=null){
            wrapper.ne("id",userId);
        }
        return sysUserMapper.selectOne(wrapper)!=null;
    }

    public PageResult<SysUser> getPageByDeptId(Integer deptId, PageQuery page){
        BeanValidator.check(page);
        QueryWrapper<SysUser> wrapper = new QueryWrapper();
        wrapper.eq("dept_id",deptId);
        IPage<SysUser> userIPage = sysUserMapper.selectPage(page,wrapper);
        if (userIPage==null){
            return PageResult.<SysUser>builder().build();
        }
        return PageResult.<SysUser>builder().total((int)userIPage.getTotal()).data(userIPage.getRecords()).build();
    }

    public List<SysUser> getAll(){
        return sysUserMapper.selectList(null);
    }
}
